package com.sinodata.bsm.cicp.finder.windows;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * <p>Title: WindowsFinder</p>
 * <p>Description: Windows发现程序的父类</p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: 北京友联创新科技</p>
 * @author credible_zhang
 * @version 1.0
 */
public abstract class WindowsFinder extends Finder {
    private static final Logger logger = Logger.getLogger(WindowsFinder.class);

    private static final String HOSTNAME_CMDSTR = "hostname";
    private String HOSTNAME = "";

    protected static final int WINDOWS_FINDER_DEFAULT_TIMEOUT = 5;

    /**
     * 获取主机名称
     * 在Windows主机资源发现的时候,设置主机的资源描述为:主机名_资源描述
     * @return String
     */
    protected final String getHostName(String ip) {
        if (!HOSTNAME.equals("")) {
            return HOSTNAME;
        }
        List<String> list = new ArrayList<String>();
        BufferedReader reader = null;
        String strLine = null;
        try {
            reader = CommandReader.getReader(ip, HOSTNAME_CMDSTR, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                list.add(strLine.trim());
            }
            if (list.size() > 0) {
                HOSTNAME = list.get(0);
                return HOSTNAME;
            }
        } catch (IOException e) {
            logger.error("failed to get hostname ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return HOSTNAME;
    }
}
